package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {
    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    IdWorker idWorker;

    @Autowired
    TimeLineService timeLineService;

    @Override
    public void publish(Movement movement) {
        //1、保存动态详情
        try {
            //设置PID
            movement.setPid(idWorker.getNextId("movement"));
            //设置时间
            movement.setCreated(System.currentTimeMillis());
            //movement.setId(ObjectId.get());
            mongoTemplate.save(movement);
//            //2、查询当前用户的好友数据
//            Criteria criteria = Criteria.where("userId").is(movement.getUserId());
//            Query query = Query.query(criteria);
//            List<Friend> friends = mongoTemplate.find(query, Friend.class);
//            //3、循环好友数据，构建时间线数据存入数据库
//            for (Friend friend : friends) {
//                MovementTimeLine timeLine = new MovementTimeLine();
//                timeLine.setMovementId(movement.getId());
//                timeLine.setUserId(friend.getUserId());
//                timeLine.setFriendId(friend.getFriendId());
//                timeLine.setCreated(System.currentTimeMillis());
//                mongoTemplate.save(timeLine);
//            }
            //写入好友的时间线表（异步写入）
            timeLineService.saveTimeLine(movement.getUserId(), movement.getId());
        } catch (Exception e) {
            //忽略事务处理
            e.printStackTrace();
        }
    }

    @Override
    public PageResult<Movement> findByUserId(Long userId, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("created")))
                .skip((long) (page - 1) * pagesize).limit(pagesize);
        List<Movement> movements = mongoTemplate.find(query, Movement.class);


        Query totalCountQuery = Query.query(criteria);
        long count = mongoTemplate.count(totalCountQuery, Movement.class);
        PageResult pageResult = new PageResult(page, pagesize, count, movements);
        return pageResult;
    }

    @Override
    public PageResult<Movement> findFriendMovements(Integer page, Integer pagesize, Long userId) {
        //查找朋友动态，同时也查找自己发布的动态
        Criteria criteria = new Criteria().orOperator(
                Criteria.where("friendId").is(userId),
                Criteria.where("userId").is(userId)

        );
//        Criteria criteria = Criteria.where("friendId").is(userId);
        Query query = Query.query(criteria)
                .skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(query, MovementTimeLine.class);
        //2、提取动态id列表
        List<ObjectId> movementIds = CollUtil.getFieldValues(movementTimeLines, "movementId", ObjectId.class);
        //根据id获取动态列表
        Query moventsQuery = Query.query(Criteria.where("id").in(movementIds)).with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(moventsQuery, Movement.class);

        //获取好友动态所有个数
        Query allCount = Query.query(Criteria.where("friendId").is(userId));
        long count = mongoTemplate.count(allCount, MovementTimeLine.class);
        return new PageResult<Movement>(page, pagesize, count, movements);
    }

    @Override
    public List<Movement> findMovementsByPids(List<Long> pids) {
        //根据pid 查找动态
        Criteria pid = Criteria.where("pid").in(pids);
        Query query = Query.query(pid);
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return movements;
    }

    //随机查询多条数据
    public List<Movement> randomMovements(Integer counts) {
        //1、创建统计对象，设置统计参数
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class, Aggregation.sample(counts));
        //2、调用mongoTemplate方法统计
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);
        //3、获取统计结果
        return results.getMappedResults();
    }

    @Override
    public Movement findById(String movementId) {
        Movement byId = mongoTemplate.findById(movementId, Movement.class);
        return byId;
    }
}
